#include "stdafx.h"
#include "Game.h"

#include "Engine.h"
#include "States.h"
#include "Filesystem.h"
#include "Log.h"

// Constants
const Vector2 back_button_pos(900.0f, 738.0f);

const RectF well_backgr_source(0.0f, 144.0f, 48.0f, 48.0f);

// Layers
const uint blocks_layer = 1;

// Filenames
const std::string tex_blocks_file = "boxes2.png";

Game::Game(RendererPtr main_renderer, BitmapFontPtr font, SpriteBatchPtr sprite_batch)
	: State(main_renderer), font(font), sprite_batch(sprite_batch)  
{
	Engine e;
	gui = e.getGUI();
}

Game::~Game()
{}

void Game::init()
{	
	TextureManagerPtr texture_mngr = this->video_device->getTextureManager();
	tex_blocks = texture_mngr->loadTexture2D("blocks", Filesystem::redirect(tex_blocks_file)); 
	reset();
	
	LOG("Game state initialized");
}

void Game::close()
{
	LOG("Game state closed");
}

void Game::render(const StateManager& state_manager)
{
	draw_well();

	if(gui->doButton(back_button_pos, "BACK"))
		state_manager.popState();
}

void Game::fade(const StateManager& state_manager, float amount, uint from, uint to)
{
	Color color = Color::lerp(Color(255, 255, 255, 0), Color(255, 255, 255, 255), amount);
	draw_well(color);
}

RectF Game::getBlockSource(BlockColor color, uint frame)
{
	assert(color < 3);
	assert(frame < 3);

	if(color == EMPTY)
		return well_backgr_source;

	RectF result;
	result.width = float(block_width);
	result.height = float(block_height);

	result.y = float((3-color) * block_height);
	result.x = float(frame * block_width);

	return result;
}

void Game::draw_well(const Color& color)
{
	for(uint y = 0; y < well_height; ++y)
	{
		for(uint x = 0; x < well_width; ++x)
		{
			RectF source = getBlockSource(well[x][y], (x^y)%3);
			
			sprite_batch->draw(tex_blocks, blocks_layer, source, 
				Vector2(float(well_x + x * block_width), float(well_y + y * block_height)), color);
		}
	}
}

void Game::reset()
{
	memset(well, 0, sizeof(well));
}